//
//  AppDelegate.m
//  HongFuShop
//
//  Created by chirui on 2017/7/25.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarVc.h"
#import "LeadVC.h"
#import "IQKeyboardManager.h"
#import "JPUSHService.h"
#import <UserNotifications/UserNotifications.h>

// 高德地图
#import <AMapFoundationKit/AMapFoundationKit.h>

#import <AMapLocationKit/AMapLocationKit.h>

#define gaoDeMapKey  @"669def418468bb6d7554c5fcfa1a4d96"


@interface AppDelegate ()<AMapLocationManagerDelegate,JPUSHRegisterDelegate>

@property(nonatomic,strong) AMapLocationManager * locationManager;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
    self.window =[[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor =[UIColor whiteColor];
    
    
    USER_DEFAULTSet(@"-200",@"lon");
    USER_DEFAULTSet(@"-200",@"lat");
    // 高德地图
    [AMapServices sharedServices].apiKey = gaoDeMapKey;
    
    self.locationManager = [[AMapLocationManager alloc] init];
    self.locationManager.delegate = self;
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //   定位超时时间，最低2s，此处设置为2s
    self.locationManager.locationTimeout =2;
    //   逆地理请求超时时间，最低2s，此处设置为2s
    self.locationManager.reGeocodeTimeout = 2;
    
    [self.locationManager startUpdatingLocation];

    
//     注册远程推送
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // 注册极光推送
    [JPUSHService setupWithOption:launchOptions appKey:@"79c98916c135b403f9ec95dd"
                          channel:@"ios"
                 apsForProduction:TRUE
            advertisingIdentifier:nil];
    
    // 注册自定义消息通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkDidReceiveMessage:)
                                                 name:kJPFNetworkDidReceiveMessageNotification
                                               object:nil];
    
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    
    //判断是否加载引导页
    NSString *lastEdition=[[NSUserDefaults standardUserDefaults] objectForKey:@"edition"];
    NSDictionary *dic=[[NSBundle mainBundle]infoDictionary];
    NSString *str=dic[@"CFBundleShortVersionString"];
    
    //    如果有新版就加载引导页
    if ([lastEdition isEqualToString:str]) {
            TabBarVc * tabbar  =[[TabBarVc alloc]init];
            self.window.rootViewController =tabbar;
            
     }else{
        self.window.rootViewController=[[LeadVC alloc]init];
    }
    [[NSUserDefaults standardUserDefaults] setValue:str forKey:@"edition"];
    [[NSUserDefaults standardUserDefaults] synchronize];

//    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
//    manager.enable = YES;
//    manager.shouldResignOnTouchOutside = YES;
//    manager.shouldToolbarUsesTextFieldTintColor = YES;
//    manager.enableAutoToolbar = NO;
    [self.window makeKeyAndVisible];

    return YES;
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    

      NSString *  latStr = [NSString stringWithFormat:@"%f",location.coordinate.latitude];
      NSString *  longStr = [NSString stringWithFormat:@"%f",location.coordinate.longitude];
    
     USER_DEFAULTSet(longStr,@"lon");
     USER_DEFAULTSet( latStr,@"lat");
    
}

// 接收到自定义消息
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    NSDictionary *userInfo = [notification userInfo];
    
    NSLog(@"%@", userInfo);
    
    UILocalNotification *localNotification = [[UILocalNotification alloc]init];
    localNotification.alertTitle = @"本地通知";
    localNotification.alertBody = userInfo[@"content"];
    [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}

-(void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler{

    NSDictionary * userInfo = notification.request.content.userInfo;
    
    NSLog(@"%@", userInfo);
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置

}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    
    NSLog(@"%@", userInfo);
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(nonnull NSDictionary *)userInfo fetchCompletionHandler:(nonnull void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    NSLog(@"%@", userInfo);
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
}

-(void)applicationDidBecomeActive:(UIApplication *)application{
    

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
